package com.cn.transfer.jobhandler;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.cn.transfer.common.constant.KeyConstant;
import com.cn.transfer.common.entity.TokenMessage;
import com.cn.transfer.common.enumeration.MessageEnum;
import com.cn.transfer.common.redis.RedisUtil;
import com.cn.transfer.common.vo.BizContentVO;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: weidian
 * @date: 2023/10/16 15:54
 * @Description: 存货编码审核新增
 */
@Slf4j
@Component
public class GetTokenXxlJob {


    @Autowired
    private RedisUtil redisUtil;

    @XxlJob("GetToken")
    public void getToken() {
        Map<String, Object> parameter = new HashMap<>();
        //接口开放平台的appTicket消息获得，请去管理后台配置消息地址
        ObjectMapper objectMapper = new ObjectMapper();
        BizContentVO bean=null;
        try {
            bean=objectMapper.readValue(JSONUtil.toJsonStr(redisUtil.get(MessageEnum.APP_TICKET.getChinese())),BizContentVO.class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        parameter.put("appTicket", bean.getAppTicket());
        // 加密证书，自建应用通过管理员授权后获得
        parameter.put("certificate", KeyConstant.CERTIFICATE);
        String jsonStr = JSONUtil.toJsonStr(parameter);
        String reult = HttpRequest.post(KeyConstant.T_URL + "/v1/common/auth/selfBuiltApp/generateToken").header("appKey", KeyConstant.APPKEY)
                .header("appSecret", KeyConstant.APPSECRET)
                .header("Content-Type", "application/json")
                .body(jsonStr)
                .execute().body();
        JSONObject jsonObject = JSONUtil.parseObj(reult);
        if (jsonObject.getStr("error") != null) {
            log.error("getToken: " + jsonObject.getStr("error"));
        }
        TokenMessage value = JSONUtil.toBean(jsonObject.getStr("value"), TokenMessage.class);

        if(value.getAccessToken()==null || value.getAccessToken().equals("")){
            redisUtil.set("token_info", redisUtil.get("token_info").toString(), -1);
        }else {
            redisUtil.set("token_info",value.getAccessToken(), -1);
        }

    }
}
